<script lang="ts">
    import { onDestroy, onMount } from "svelte";
    import { FloatButton } from "../FloatButton";
    import type { BackTopProps } from "./BackTop";

    const props: BackTopProps = $props();

    const visibilityHeight = props.visibilityHeight ?? 400;

    let visible = $state(false);
    let el = $derived.by(() => {
        return props.target ? props.target() : window;
    });

    $effect(() => {
        if (el) {
            el.removeEventListener("scroll", handleScroll);
            el.addEventListener("scroll", handleScroll);
        }
    });

    const handleScroll = () => {
        const offset = el === window ? window.pageYOffset : (el as HTMLElement).scrollTop;
        visible = offset >= visibilityHeight;
    };

    const onClick = () => {
        el?.scrollTo({ top: 0, behavior: "smooth" });
        props.onclick?.();
    };

    onMount(() => {
        window.addEventListener("resize", handleScroll);
    });

    onDestroy(() => {
        el?.removeEventListener("scroll", handleScroll);
        window.removeEventListener("resize", handleScroll);
    });
</script>

{#if visible}
    <FloatButton {...props} onclick={onClick}></FloatButton>
{/if}
